package com.tju.resource.tool.tool;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author HyEISN
 */
public class QuickQuery {

    /**
     * Query mode equal.
     */
    public static final String EQUALS = "EQUALS";

    /**
     * Query mode like.
     */
    public static final String LIKE = "LIKE";

    /**
     * Return link params, example: QuickQuery.params().put("name", "Mike")
     */
    public static JSONObject params() {
        return JSONUtil.parseObj("{}");
    }

    /**
     * Return query record list.
     *
     * @param mapper model mapper
     * @param params query params, just like json string: QuickQuery.params().putOnce("name", "asd").putOnce("age", 99)
     */
    public static <T> List<T> list(BaseMapper<T> mapper, JSONObject params) {
        QueryWrapper<T> query = new QueryWrapper<>();

        params.forEach(query::eq);

        return mapper.selectList(query);
    }

    /**
     * Customer query type, like or equals.
     *
     * @param params example: QuickQuery.params().putOnce("name", "asd," + QuickQuery.LIKE).putOnce("age", 99 + QuickQuery.EQUALS)
     * */
    public static <T> List<T> custom(BaseMapper<T> mapper, JSONObject params) {
        QueryWrapper<T> query = new QueryWrapper<>();

        params.forEach((k, v) -> {
            String values[] = v.toString().split(",");

            if (StringUtils.equals(values[1], EQUALS)) {
                query.eq(k, values[0]);
            } else if (StringUtils.equals(values[1], LIKE)) {
                query.like(k, values[0]);
            }
        });

        return mapper.selectList(query);
    }

}
